-module(common).
-export([complete_mkdir/1, image_md5/1, validate_userchnl/2,
		image_format/1, get_image_extension/1, get_imagefile_path/4,
		create_file/2, get_internalfile_path/3]).

complete_mkdir(Path) ->
	[H|T] = filename:split(Path),
	complete_mkdir(H, T).
complete_mkdir(_, []) ->
	ok;
complete_mkdir(H, [M|N]) ->
	Path = lists:append([H, "/", M]),
	case file:make_dir(Path) of
		ok ->
			complete_mkdir(Path, N);
		{error, eexist} ->
			complete_mkdir(Path, N);
		{error, Reason} ->
			{error, Reason}
	end.

image_md5(FileData) ->
	lists:flatten([io_lib:format("~2.16.0b", [X]) || X <- binary_to_list(erlang:md5(FileData))]).

validate_userchnl(0, _) ->
	throw({imaged_error, "username length is zero."});
validate_userchnl(_, 0) ->
	throw({imaged_error, "sitename length is zero."});
validate_userchnl(_, _) ->
	ok.

image_format(".gif") ->
	0;
image_format(".bmp") ->
	1;
image_format(".png") ->
	2;
image_format(".jpg") ->
	3;
image_format(".jpeg") ->
	4;
image_format(FileExt) ->
	errlogs:errlog("do not support this file extension[~p].~n", [FileExt]),
	throw({imaged_error, "do not support this file extension."}).

get_image_extension(0) ->
	".gif";
get_image_extension(1) ->
	".bmp";
get_image_extension(2) ->
	".png";
get_image_extension(3) ->
	".jpg";
get_image_extension(4) ->
	".jpeg";
get_image_extension(FormatType) ->
	errlogs:errlog("get file extension fail[~p].~n", [FormatType]),
	throw({imaged_error, "get file extension fail."}).

get_imagefile_path(Path, {Year, Month, Day}, ImageId, ImageFormat) ->
	lists:append(filename:join([Path, integer_to_list(Year), integer_to_list(Month), integer_to_list(Day), integer_to_list(ImageId div 100), integer_to_list(ImageId)]), get_image_extension(ImageFormat)).

get_internalfile_path(Path, {Year, Month, Day}, ImageId) ->
	filename:join([Path, integer_to_list(Year), integer_to_list(Month), integer_to_list(Day), integer_to_list(ImageId div 100)]).

create_file(FileName, FileData) ->
	Path = filename:dirname(FileName),
	case complete_mkdir(Path) of
		ok ->
			case file:write_file(FileName, FileData) of
				ok ->
					FileName;
				{error, Reason} ->
					errlogs:errlog("imaged create_file fail[~p:~p].~n", [Reason, FileName]),
					throw({imaged_error, Reason})
			end;
		{error, Reason} ->
			errlogs:errlog("imaged create_file fail[~p:~p].~n", [Reason, Path]),
			throw({imaged_error, Reason})
	end.



